<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckPhoneCode
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $request->validate([
                               'phone' => 'required|regex:/^1[3456789]\d{9}$/',
                               'code'  => 'required',
                           ],
                           [
                               'code.required'  => '请输入验证码',
                           ]);
        // 验证code是否正确
        $code = cache('phone_code_' . $request->input('phone'));
        if ($code != $request->input('code')) {
            abort(400, '验证码或手机号错误');
        }
        return $next($request);
    }
}
